package com.rfy.framework.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;


public class EncryptorUtil {

	/**
	 * encryption key
	 */
	private final static String ENCRYPT_KEY = "JWk3+vabpOkxubZBB8X2gA==";

	/**
	 * initial vector
	 */
	private final static String INITVECTOR = "DepponNewWebsite";

	/**
	 * 加密
	 * @param strToEncrypt
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String strToEncrypt) throws Exception {
		if(!StringUtil.isNotEmpty(strToEncrypt)){
			IvParameterSpec iv = new IvParameterSpec(INITVECTOR.getBytes("UTF-8"));
			SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(ENCRYPT_KEY), "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
			byte[] encryptedData = cipher.doFinal(strToEncrypt.getBytes());
			return Base64.getEncoder().encodeToString(encryptedData);
		}
		return null;
	}
	
	/**
	 * 解密
	 * @param encryptedStr
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(Object encryptedStr) throws Exception {
		IvParameterSpec iv = new IvParameterSpec(EncryptorUtil.INITVECTOR.getBytes("UTF-8"));
		SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(EncryptorUtil.ENCRYPT_KEY), "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
		return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedStr.toString())));
	}
}
